#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <unistd.h>

#define FIFO_PHONE "/tmp/phone_fifo"
#define FIFO_UI "/tmp/ui_fifo"

int fifo_phone = -1;
int fifo_ui = -1;

// 非阻塞
static int get_char() {
  fd_set rfds;
  struct timeval tv;

  FD_ZERO(&rfds);
  FD_SET(0, &rfds);
  tv.tv_sec = 0;
  tv.tv_usec = 1; // 设置超时等待时间

  return select(1, &rfds, NULL, NULL, &tv) > 0 ? getchar() : 0;
}

void init_fifo() {
  // phone fifo
  if (access(FIFO_PHONE, F_OK)) {
    if (-1 == mkfifo(FIFO_PHONE, 0666)) {
      perror("create fifo_phone error!\n");
      exit(-1);
    }
  }

  fifo_phone = open(FIFO_PHONE, O_RDWR | O_NONBLOCK);

  if (fifo_phone == -1) {
    perror("open fifo_phone error");
    exit(-1);
  }

  // ui fifo
  if (access(FIFO_UI, F_OK)) {
    if (-1 == mkfifo(FIFO_UI, 0666)) {
      perror("create fifo_ui error");
      exit(-1);
    }
  }

  // fifo_ui = open(FIFO_UI, O_WRONLY | O_NONBLOCK, 0);
  fifo_ui = open(FIFO_UI, O_RDWR | O_NONBLOCK);

  if (fifo_ui == -1) {
    perror("open fifo_ui error");
    exit(-1);
  }

  puts("init fifo finished.");
}

void hangup() {
  // 给 phone 发送 ui 终止消息
  char msg[] = "ui_quit";
  write(fifo_ui, msg, strlen(msg) + 1);
  printf("Send ui quit msg...\n");
}

int main() {
  char buf[256] = {0};
  int len;

  init_fifo();

  while (true) {
    // 先读取 phone 线程的信息，判断对方是否挂断
    bzero(buf, sizeof(buf));

    len = read(fifo_phone, buf, sizeof(buf));

    if (len > 0) {
      if (strcmp(buf, "phone_quit") == 0) {
        printf("Task phone hangup.\n");
        break;
      }
    }

    int ch = get_char();

    if (ch == 'c')
      break;

    if (ch == 'q')
      hangup();
  }

  close(fifo_phone);
  close(fifo_ui);

  return 0;
}
